<template>
  <div class="server-page">
    <!-- 要渲染4个模型 放开注释 -->
    <!-- <div class="btn-box">
      <div class="btns prev-btn" @click="goPrev">
        <img src="../assets/images/prev.png" alt="">
      </div>
      <span>服务器 {{num}}</span>
      <div class="btns next-btn" @click="goNext">
        <img src="../assets/images/next.png" alt="">
      </div>
    </div> -->
    <div
      class="serverImg-box"
      :id="'container'+id"
    >
      <!-- <img src="../assets/images/server.png" alt=""> -->
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
//引入three.js库
import * as THREE from 'three'
//引入.obj和.mtl文件加载器
import { MTLLoader, OBJLoader } from 'three-obj-mtl-loader';
//引入轨道控制器
var OrbitControls = require('three-orbit-controls')(THREE)


export default {
  props: ['num', 'id'],
  data() {
    return {
      // num:1
      camera: null,
      scene: null,
      renderer: null,
      mesh: null,
      control: null,
      transformCtrl: null,
      orbit: null,
      raycaster: null,
      mouse: null,
      container: null,
      object: null,
      group: null
    }
  },
  components: {

  },
  mounted() {
    setTimeout(() => {
      this.init();
      this.render();
    }, 0)
    // this.initWebSocket();
    // this.animate();
    // window.addEventListener( 'click', this.onMouseClick, false )
  },
  // update(){
  //   this.init();
  // },
  destroyed() {
    // window.removeEventListener('resize',this.onWindowResize);
    // window.removeEventListener('click',this.onMouseClick);
  },
  methods: {
    goPrev() {
      console.log('jian')
      // if(this.num>0){
      //   this.num-=1;
      // }
    },
    goNext() {
      console.log('jia')
      // this.num=this.num+1;
    },
    init() {
      var _this = this;
      this.container = document.getElementById('container' + this.id);
      console.log('this.container>>>', this.container)
      console.log(this.container.left, this.container.top)
      //创建渲染器
      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,// 默认情况下为黑色场景，此处设置为透明（即白色场景）
      });
      //设置像素比
      this.renderer.setPixelRatio(window.devicePixelRatio);
      //设置渲染器的宽高
      this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
      //添加到容器中
      this.container.appendChild(this.renderer.domElement);
      //创建cameara
      this.camera = new THREE.PerspectiveCamera(75, this.container.clientWidth / this.container.clientHeight, 1, 3000);
      //创建camera位置
      this.camera.position.set(0, 0, 1500)
      this.camera.lookAt(0, 0, 0)
      this.group = new THREE.Group();
      //创建场景
      this.scene = new THREE.Scene();
      // this.scene.add( new THREE.GridHelper( 3000, 15 ) );
      this.scene.add(this.group)
      //创建光源
      //平行光设置
      var directionalLight = new THREE.DirectionalLight(0x383838);

      // 平行光配置
      directionalLight.position.set(300, 100, 2000);
      // directionalLight.castShadow = true;
      // directionalLight.shadow.camera.near = 20;
      // directionalLight.shadow.camera.far = 500;
      // directionalLight.shadow.camera.left = -500;
      // directionalLight.shadow.camera.right = 500;
      // directionalLight.shadow.camera.top = 500;
      // directionalLight.shadow.camera.bottom = -500;

      // 距离和强度
      directionalLight.distance = 30;
      directionalLight.intensity = .6;

      // 设置阴影的分辨率
      // directionalLight.shadow.mapSize.width = 1024;
      // directionalLight.shadow.mapSize.height = 1024;

      this.scene.add(directionalLight);

      var ambientColor = '0x0c0c0c';
      var ambientLight = new THREE.AmbientLight(ambientColor);
      this.scene.add(ambientLight);


      //创建轨道控制器 传入camera
      this.orbit = new OrbitControls(this.camera, this.renderer.domElement);
      this.orbit.update();
      // this.orbit.addEventListener( 'change', this.render
      // window.addEventListener( 'resize', this.onWindowResize, false );


      this.loadMtlAndObj({
        MtlUrl: 'static/models/s3.mtl',
        ObjUrl: 'static/models/s3.obj',
        x: 0,
        y: 0,
        z: 0,
        scale: 300
      });
    },
    onWindowResize() {
      this.camera.aspect = window.innerWidth / window.innerHeight;
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.render();
    },
    //封装MTL OBJ模型加载方法
    /**
     * @param params 对象类型
     * @param params.MtlUrl Mtl文件路径
     * @param params.ObjUrl Obj文件路径
     * @param params.scale 缩放比
     * @param params.x y z  位置
     * @param params.zhou arr['x|y|z',val]  旋转
     * @return:
     */
    loadMtlAndObj(params) {
      var _this = this;
      var mtlLoader = new MTLLoader();
      mtlLoader.load(
        params.MtlUrl,
        function (materials) {
          var objLoader = new OBJLoader();
          objLoader.setMaterials(materials);
          objLoader.load(params.ObjUrl,
            function (object) {
              object.traverse(function (child) {
                child.castShadow = false;// 是否启用阴影选项
                if (child instanceof THREE.Mesh) {
                  //child.material.map = texture;
                }
              });
              // object.getName('name');
              object.position.x = params.x || 0;
              object.position.y = params.y || 0;
              object.position.z = params.z || 0;

              object.scale.x = params.scale || 1;
              object.scale.y = params.scale || 1;
              object.scale.z = params.scale || 1;
              if (params.zhou) {
                switch (params.zhou[0]) {
                  case 'x':
                    object.rotation.x = params.zhou[1];
                    break;
                  case 'y':
                    console.log('params.zhou[0]>>', params.zhou[0])
                    object.rotation.y = params.zhou[1];
                    break;
                  case 'z':
                    object.rotation.z = params.zhou[1];
                    break;
                }
              }
              // object.rotation.x = THREE.Math.degToRad( 90 );
              object.children[0].geometry.computeBoundingBox();
              object.children[0].geometry.center()
              _this.group.add(object);
              // _this.scene.add(object);

            }
          )
        }
      )
    },
    //渲染
    render() {
      this.renderer.render(this.scene, this.camera); // 结合场景和相机进行渲染，即用摄像机拍下此刻的场景
      this.group.rotation.y += 0.005;

      requestAnimationFrame(this.render); // 让浏览器执行参数中的函数，不断循环（浏览器一个新的API）

    },
    //设置3d动态效果
    animate() {
      requestAnimationFrame(this.animate);
      // this.mesh.rotation.x += 0.01;
      // this.group.rotation.y += 5;
      // this.camera.position.x=this.camera.position.x+100;
      this.renderer.render(this.scene, this.camera);
    }
  }
}
</script>

<style scoped lang='scss'>
.server-page {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 354px;
  height: 80%;

  .btn-box {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 0 20px;
    width: 100%;
    height: 76px;

    span {
      font-size: 22px;
      font-weight: 800;
      background: linear-gradient(to bottom, #d1e4ec, #8beaf7);
      -webkit-background-clip: text;
      color: transparent;
    }
  }

  .serverImg-box {
    display: flex;
    width: 100%;
    // flex: 1;
    height: 80%;
    justify-content: center;
    align-items: center;
  }
}
</style>
